package edu.gatech.ors.mrsim.io.conf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;

import org.apache.log4j.Logger;

public abstract class ConfigurableClass implements Configurable {
	protected Configuration configuration;
	private boolean successfulLoad;

	public ConfigurableClass(Configuration config) {
		this.configuration = config;
	}

	public abstract String getName();

	protected Configuration checkForRedirect(Logger logger) {
		if (hasConfigurationRedirect())
			return getConfigurationRedirect(logger);
		return configuration;
	}

	protected boolean hasConfigurationRedirect() {
		if (configuration != null) {
			return configuration.containsKey(getName() + " Configuration");
		}
		return false;
	}

	protected Configuration getConfigurationRedirect(Logger logger) {
		String name = getName();
		String redirect = name + " Configuration";
		if (!configuration.containsKey(redirect))
			return configuration;
		File otherConfig = configuration.getFile(redirect);
		try {
			Configuration redirectConfig = new PropertiesConfiguration(otherConfig);
			return redirectConfig;
		} catch (InvalidPropertiesFormatException e) {
			logger.error("Configuration file for Module " + name + " has invalid format.", e);
		} catch (FileNotFoundException e) {
			logger.error("Configuration file for Module " + name + " not found.", e);
		} catch (IOException e) {
			logger.error("Configuration file for Module " + name + " got IO error.", e);
		}
		return null;
	}

	@Override
	public Configuration getConfiguration() {
		return configuration;
	}

	@Override
	public void setConfiguration(Configuration config) {
		configuration = config;
	}

	public boolean isSuccessfulLoad() {
		return successfulLoad;
	}

}
